//
//  AlertsViewController.m
//  Againstpoor
//
//  Created by 辰领科技 on 16/11/6.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "AlertsViewController.h"
#import "AlertsTableViewCell.h"
#import "AlertsDetailViewController.h"
#import "AboutViewController.h"

static NSString * Identifier = @"tableViewCell";
@interface AlertsViewController ()
<UITableViewDelegate,UITableViewDataSource>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (weak, nonatomic) IBOutlet UILabel *titleLabel;

@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) NSMutableArray *array;

@end

@implementation AlertsViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if ([_ID isEqualToString:@"1"]) {
        _titleLabel.text = @"扶贫快讯";
    } else {
        _titleLabel.text = @"政策法规";
    }
    [self.tableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _pageNO = 1;
    _array = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
}
- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self getalertsList];
        });
    }];
    [_tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.array.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self getalertsList];
        });
    }
}
#pragma mark - 扶贫快讯
- (void)getalertsList {
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:[NSString stringWithFormat:@"%d",_pageNO] forKey:@"pageNum"];
    [dic setObject:[NSString stringWithFormat:@"%d",PageSize] forKey:@"pageSize"];
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:dic withPath:F_articlesList withHttpType:@"POST" withTag:F_F_articlesList];
}

#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _array.count;
    
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 95*VerticalRatio();
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    AlertsTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:Identifier];
    if (cell == nil) {
        cell= [[AlertsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifier];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    NSDictionary *dic = _array[indexPath.row];

    NSString *image = [NSString stringWithFormat:@"%@",dic[@"artiImage"]];
    if (image && image.length>0 && ![dic[@"museImage"] isEqual:[NSNull null]]) {
        [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://119.84.26.90:8082/againstpoor/upload/tmp/%@",image]]];
    }
    cell.titleLabel.text = [Common stringFromData:dic[@"artiName"]];
    cell.detailLabel.text = [Common stringFromData:dic[@"artiContent"]];
    [cell.nameButton setTitle:[Common stringFromData:dic[@"artiAuthor"]] forState:UIControlStateNormal];
    [cell.timeButton setTitle:[Common stringFromData:dic[@"artiCreateTime"]] forState:UIControlStateNormal];
    return cell;
}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
    AboutViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"About"];
    page.type = 3;
    page.artiId = [Common stringFromData:_array[indexPath.row][@"artiId"]];
    [[Common getNavigation]pushViewController:page];
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.footer endRefreshing];
    [_tableView.header endRefreshing];
    if (tag==F_F_articlesList) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.array removeAllObjects];
                }
                
                NSArray *arr = database[@"rows"];
                for (id entity in arr) {
                    [self.array addObject:entity];
                }

                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
            });
        }else  {
            
        }
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [_tableView.footer endRefreshing];
    [_tableView.header endRefreshing];
    [self dismissWaitDialog];
    
    
}

@end
